<template>
  <div class="wrapper">
    <div id="app">
      <!-- 复用导航栏 -->
      <nav class="nav-bar">
        <div class="nav-left">
          <router-link to="/" class="nav-link">首页</router-link>
          <router-link to="/contact" class="nav-link">购物车</router-link>
          <router-link to="/about" class="nav-link">我的订单</router-link>
          <router-link to="/user" class="nav-link">我的</router-link>
        </div>
        <div class="nav-right">
          <router-link to="/sign" class="nav-link" v-if="!isLoggedIn">注册/登录</router-link>
          <div v-else class="user-info">
            <span>{{ userInfo.name }}</span>
            <el-button type="text" @click="handleLogout">退出登录</el-button>
          </div>
        </div>
      </nav>

      <!-- 注册/登录表单容器 -->
      <div class="content sign-container">
        <!-- 切换标签 -->
        <div class="tab-switch">
          <el-button 
            type="primary" 
            :class="{ 'active': isLogin }" 
            @click="switchTab(true)"
          >
            登录
          </el-button>
          <el-button 
            type="primary" 
            :class="{ 'active': !isLogin }" 
            @click="switchTab(false)"
          >
            注册
          </el-button>
        </div>

        <!-- 表单卡片 -->
        <el-card class="sign-card">
          <el-form 
            :model="formData" 
            :rules="isLogin ? loginRules : registerRules" 
            ref="formRef"
            label-width="80px"
            class="sign-form"
          >
            <!-- 登录用手机号，注册用用户名 -->
            <el-form-item 
              :label="isLogin ? '手机号码' : '用户名'" 
              :prop="isLogin ? 'phone' : 'username'"
            >
              <el-input 
                v-model="formData[isLogin ? 'phone' : 'username']" 
                :placeholder="isLogin ? '请输入手机号码' : '请输入用户名'" 
              />
            </el-form-item>

            <!-- 密码 -->
            <el-form-item label="密码" prop="password">
              <el-input v-model="formData.password" type="password" placeholder="请输入密码" />
            </el-form-item>

            <!-- 注册特有字段：确认密码 -->
            <el-form-item 
              label="确认密码" 
              prop="confirmPassword" 
              v-if="!isLogin"
            >
              <el-input v-model="formData.confirmPassword" type="password" placeholder="请再次输入密码" />
            </el-form-item>

            <!-- 注册特有字段：手机号码 -->
            <el-form-item 
              label="手机号码" 
              prop="phone" 
              v-if="!isLogin"
            >
              <el-input v-model="formData.phone" placeholder="请输入手机号码" />
            </el-form-item>

            <!-- 提交按钮 -->
            <el-form-item>
              <el-button 
                type="primary" 
                class="submit-btn" 
                @click="submitForm"
              >
                {{ isLogin ? '登录' : '注册' }}
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElLoading } from 'element-plus';

// 创建axios实例
const api = axios.create({
  baseURL: 'http://127.0.0.1:8080',
  timeout: 5000
});

export default {
  name: 'SignView',
  data() {
    // 手机号唯一性验证
    const validatePhoneUnique = async (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号码'));
        return;
      }
      
      // 先验证格式
      if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码格式'));
        return;
      }

      try {
        // 调用后端接口检查手机号是否已存在
        const res = await api.get(`/users/checkPhone?phone=${value}`);
        if (res.data.exists) {
          callback(new Error('该手机号码已被注册'));
        } else {
          callback();
        }
      } catch (err) {
        console.error('手机号验证失败', err);
        callback(new Error('验证失败，请稍后重试'));
      }
    };

    return {
      isLogin: true,
      isLoggedIn: false,
      userInfo: {},
      formData: {
        username: '',    // 注册用用户名
        phone: '',       // 手机号（登录和注册都用）
        password: '',
        confirmPassword: ''
      },
      formRef: null,

      // 登录表单验证规则（手机号+密码）
      loginRules: {
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码格式', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },

      // 注册表单验证规则（增加手机号唯一性验证）
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              if (value !== this.formData.password) {
                callback(new Error('两次密码输入不一致'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码格式', trigger: 'blur' },
          { validator: validatePhoneUnique, trigger: 'blur' }  // 唯一性验证
        ]
      }
    };
  },

  created() {
    // 页面加载时检查登录状态（增加容错处理）
    try {
      const storedUser = localStorage.getItem('userInfo');
      if (storedUser) {
        this.userInfo = JSON.parse(storedUser || '{}');
        this.isLoggedIn = true;
      }
    } catch (err) {
      console.error('解析用户信息失败', err);
      // 清除错误的本地存储数据
      localStorage.removeItem('userInfo');
      localStorage.removeItem('userId');
      this.isLoggedIn = false;
      this.userInfo = {};
    }
  },

  methods: {
    // 切换登录/注册表单
    switchTab(isLogin) {
      this.isLogin = isLogin;
      this.formData = {
        username: '',
        phone: '',
        password: '',
        confirmPassword: ''
      };
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
    },

    // 安全的退出登录方法（重点优化）
    handleLogout() {
      try {
        // 清除本地存储（增加容错处理）
        if (localStorage) {
          localStorage.removeItem('userInfo');
          localStorage.removeItem('userId');
        }
        
        // 重置状态
        this.isLoggedIn = false;
        this.userInfo = {};
        
        // 显示成功消息并跳转
        ElMessage.success('已退出登录');
        this.$router.push('/').catch(err => {
          // 捕获路由跳转可能的错误
          console.warn('路由跳转失败', err);
        });
      } catch (err) {
        console.error('退出登录过程出错', err);
        // 即使出错也尽量保证状态正确
        this.isLoggedIn = false;
        this.userInfo = {};
        ElMessage.success('已退出登录');
      }
    },

    // 提交表单（登录/注册）
    async submitForm() {
      // 表单验证（增加容错）
      let valid = false;
      try {
        valid = await this.$refs.formRef.validate();
      } catch (err) {
        console.warn('表单验证失败', err);
        return;
      }
      if (!valid) return;

      const loading = ElLoading.service({ text: '处理中...' });

      try {
        if (this.isLogin) {
          // 登录请求：使用手机号和密码
          const res = await api.post('/users/login', {
            phone: this.formData.phone,
            password: this.formData.password
          });

          // 登录成功处理
          this.userInfo = res.data || {};
          this.isLoggedIn = true;
          localStorage.setItem('userInfo', JSON.stringify(this.userInfo));
          localStorage.setItem('userId', this.userInfo.id || ''); // 存储用户ID
          ElMessage.success('登录成功');
          this.$router.push('/').catch(err => {
            console.warn('登录后跳转失败', err);
          });
        } else {
          // 注册请求
          const res = await api.post('/users', {
            name: this.formData.username,
            phone: this.formData.phone,
            password: this.formData.password,
            address: ''
          });

          if (res.data > 0) {
            ElMessage.success('注册成功，请登录');
            this.switchTab(true); // 切换到登录
          } else {
            ElMessage.error('注册失败，请重试');
          }
        }
      } catch (err) {
        console.error('提交表单出错', err);
        const errorMsg = err.response?.data?.message || 
                        (this.isLogin ? '登录失败：手机号或密码错误' : '注册失败');
        ElMessage.error(errorMsg);
      } finally {
        loading.close();
      }
    }
  }
};
</script>

<style scoped>
/* 保持原有样式不变 */
.wrapper {
  padding: 20px;
}
.content {
  padding-top: 60px;
  max-width: 800px;
  margin: 0 auto;
}
.tab-switch {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  gap: 10px;
}
.tab-switch .el-button {
  min-width: 120px;
}
.tab-switch .el-button.active {
  background-color: #6b46c1;
  border-color: #6b46c1;
}
.sign-card {
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
.sign-form {
  max-width: 500px;
  margin: 0 auto;
}
.submit-btn {
  width: 100%;
  margin-top: 10px;
}
.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}
.nav-left {
  display: flex;
  gap: 20px;
}
.nav-right {
  display: flex;
  align-items: center;
  gap: 10px;
}
.nav-link {
  text-decoration: none;
  color: #333;
  padding: 5px 10px;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
}
.nav-link.router-link-exact-active {
  color: #6b46c1;
  border-bottom-color: #6b46c1;
}
.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #333;
}
</style>